﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;


namespace Ession
{
    /// <summary>
    /// 以GET和POST访问网站 ,不过似乎只能同时访问两个
    /// </summary>
    public class AutoPost
    {
        public AutoPost()
        {
            cookie = new CookieContainer();

        }
        public static CookieContainer cookie;
        public int currentDownLoadSize;
        public static HttpWebRequest request;
        public static HttpWebResponse response;
        public int totalsize;
        public string url = "";


        public string DownLoadData(string URL, Encoding en)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookie;
                response = request.GetResponse() as HttpWebResponse;
                //得到最大长度
                totalsize = int.Parse(response.Headers["Content-Length"]);

                StreamReader sr = new StreamReader(response.GetResponseStream());
                string data = "";
                char[] buffer = new char[1024];
                int readcount = 0;
                readcount = sr.ReadBlock(buffer, 0, buffer.Length);
                data = en.GetString(en.GetBytes(buffer));
                currentDownLoadSize += readcount;//加上
                while (readcount != 0)
                {
                    readcount = sr.ReadBlock(buffer, 0, buffer.Length);
                    data += en.GetString(en.GetBytes(buffer));
                    currentDownLoadSize += readcount;//加上
                }

                return data;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public static string GetEventValidation(string srcString)
        {
            // 获取页面的 EventValidation                
            string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
            int i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
            int j = srcString.IndexOf("\"", i);
            return srcString.Substring(i, j - i);
        }
        public static string getHiddenFieldValue(string valueName, string html)
        {
            try
            {
                string key = "hidden\" name=\"" + valueName;
                int i = html.IndexOf(key);
                i = html.IndexOf("value=", i);
                int j = html.IndexOf("\"", i + 7);
                return html.Substring(i + 7, j - i - 7);
            }
            catch (Exception ex)
            {
                return "";
            }


        }

        /// <summary>
        /// 以Get方式访问网址
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public string GetHtml(string URL, IWebProxy proxy = null)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)";
                //   request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookie;
                if (proxy != null)
                {
                    request.Proxy = proxy;
                    request.UseDefaultCredentials = true;
                }

                response = request.GetResponse() as HttpWebResponse;
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 以Get方式访问网址
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public byte[] GetHtmlData(string URL, IWebProxy proxy = null)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)";
                //   request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookie;
                if (proxy != null)
                {
                    request.Proxy = proxy;
                    request.UseDefaultCredentials = true;
                }

                response = request.GetResponse() as HttpWebResponse;

                Stream stream = response.GetResponseStream();
                long contentLength = response.ContentLength;
                byte[] outBytes = new byte[contentLength];
                outBytes = ReadFully(stream);
                stream.Close();
                return outBytes;

            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 以异步Get方式访问网址
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        public string GetHtmlAsyc(string URL)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookie;

                var ia = request.BeginGetResponse(
                    (s) =>
                    {
                        if (s.IsCompleted)
                        {

                        }
                    }, this
                    );
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static byte[] GetHtmlByBytes(string URL)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookie;
                response = request.GetResponse() as HttpWebResponse;
                Stream stream = response.GetResponseStream();
                long contentLength = response.ContentLength;
                byte[] outBytes = new byte[contentLength];
                outBytes = ReadFully(stream);
                stream.Close();
                return outBytes;
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        public static Stream GetStreamByBytes(string URL)
        {
            try
            {
                Stream stream = new MemoryStream(GetHtmlByBytes(URL));
                return stream;
            }
            catch (Exception ex)
            {
                return null;
            }


        }
        public static string getViewState(string srcString)
        {
            // 获取页面的 VeiwState                
            string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
            int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
            int j = srcString.IndexOf("\"", i);
            return srcString.Substring(i, j - i);



        }
        /// <summary>
        /// 自动跳转
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="postData"></param>
        /// <param name="en"></param>
        /// <returns></returns>
        //public string PostDataAndGo(string URL, string postData, Encoding en)
        //{
        //    request = HttpWebRequest.Create(URL) as HttpWebRequest;
        //    request.Method = "POST";
        //    request.ContentType = "application/x-www-form-urlencoded";
        //    request.CookieContainer = cookie;
        //    byte[] postBytes = en.GetBytes(postData);
        //    request.ContentLength = postBytes.Length;
        //    Stream newStream = request.GetRequestStream();
        //    newStream.Write(postBytes, 0, postBytes.Length);
        //    newStream.Close();
        //    //post 结束
        //    //返回HTML
        //    response = (HttpWebResponse)request.GetResponse();
        //    Stream dataStream = response.GetResponseStream();

        //    //   StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("gb2312"));
        //    StreamReader reader = new StreamReader(dataStream, en);

        //    string data= reader.ReadToEnd();
        //    //if ()
        //    //{

        //    //}

        //}
        //public bool ContainAutoGo(string data)
        //{
        //    //if (data.IndexOf(""))
        //    //{

        //    //}
        //}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="postData"></param>
        /// <param name="en">读取时的编码</param>
        /// <returns></returns>
        public string PostData(string URL, string postData, Encoding en, int timeOut = 10000, IWebProxy proxy = null)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "POST";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)";
                request.ContentType = "application/x-www-form-urlencoded";
                if (proxy != null)
                {
                    request.Proxy = proxy;
                    request.UseDefaultCredentials = true;

                }
                request.Timeout = timeOut;
                request.CookieContainer = cookie;
                byte[] postBytes = en.GetBytes(postData);
                request.ContentLength = postBytes.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(postBytes, 0, postBytes.Length);
                newStream.Close();
                //post 结束
                //返回HTML
                response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();

                //   StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("gb2312"));
                StreamReader reader = new StreamReader(dataStream, en);

                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
            }

        }
        public bool PostData(string URL, string postData, Encoding en, string headerKey, Func<string, bool> cc, int timeOut = 10000, IWebProxy proxy = null)
        {
            try
            {
                request = HttpWebRequest.Create(URL) as HttpWebRequest;
                request.Method = "POST";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1)";
                request.ContentType = "application/x-www-form-urlencoded";
                if (proxy != null)
                {
                    request.Proxy = proxy;
                    request.UseDefaultCredentials = true;

                }
                request.Timeout = timeOut;
                request.CookieContainer = cookie;
                byte[] postBytes = en.GetBytes(postData);
                request.ContentLength = postBytes.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(postBytes, 0, postBytes.Length);
                newStream.Close();
                //post 结束
                //返回HTML
                response = (HttpWebResponse)request.GetResponse();

                //   Stream dataStream = response.GetResponseStream();

                //   StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("gb2312"));
                //StreamReader reader = new StreamReader(dataStream, en);
                if (cc(response.GetResponseHeader(headerKey)))
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[128];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
    }
}
